package com.myidis.servlet;

import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.myidis.entity.Department;
import com.myidis.mapper.DeptMapper;
import com.myidis.response.DepartmentRes;

@Service
public class DeptServlet {
	@Autowired
	private DeptMapper deptMapper;
	
	/*
	 * 获取树状部门列表
	 * @return DepartmentRes
	 */
	public DepartmentRes all() {
		int parent_index = 0;	
		int parent_id = 0;
		DepartmentRes res = new DepartmentRes();
		List<Department> depts = deptMapper.all();
		List<DepartmentRes> list = new ArrayList<DepartmentRes>();
		list.add(res);
		
		for(Department dept: depts) {
			DepartmentRes temp = new DepartmentRes(dept);
			list.add(temp);
			
			if(dept.getParent() != parent_id) {
				list.remove(parent_index);
				for(int i = 0; i < list.size(); i++)
					if(list.get(i).getId() == dept.getParent()) {
						parent_index = i;
						break;
					}
				parent_id = list.get(parent_index).getId();
			}
			list.get(parent_index).children.add(temp);
		}
		return res;
	}
	
	/*
	 * 获取所有部门信息
	 * @return List<Department>
	 */
	public List<Department> getAll() {
		return deptMapper.all();
	}
	
	/*
	 * 获取一个部门的信息
	 * @param int
	 * @return Department
	 */
	public Department getOne(int id) {
		return deptMapper.getOne(id);
	}
	
	/*
	 * 添加一个部门
	 * @param Department
	 * @return int
	 */
	public int insert(Department dept) {
		return deptMapper.insert(dept);
	}
	
	/*
	 * 添加一组部门
	 * @param List<Department>
	 * @return int
	 */
	public int insertAll(List<Department> objs) {
		int count = 0;
		for (Department obj: objs) {
			count += deptMapper.insert(obj);
		}
		return count;
	}
	
	/*
	 * 修改一个部门
	 * @param Department
	 * @return int
	 */
	public int update(Department dept) {
		dept.setParent(deptMapper.getOne(dept.getId()).getParent());
		return deptMapper.update(dept);
	}
	
	/*
	 * 删除一个部门
	 * @param int
	 * @return int
	 */
	public int delete(int id) {
		int count = 0;
		count += deptMapper.delete(id);
		List<Department> children = deptMapper.getByParent(id);
		for(Department child: children) {
			count += this.delete(child.getId());
		}
		return count;
	}
	
	/*
	 * 删除一组部门
	 * @param List<IDReq>
	 * @return int
	 */
	public int deleteAll(int[] ids) {
		int count = 0;
		for(int id: ids)
			count += this.delete(id);
		return count;
	}
}
